/**
 * @Title: ApiOrderController
 * @Package cn.com.yiqi.wsc.api.controller
 * @Description: TODO
 * Copyright: Copyright (c) 2016
 * Company: 成都壹柒互动科技有限公司
 * @author 会员系统组-林威
 * @date 2017/3/1 11:15
 * @version V1.0
 */
package cn.com.yiqi.wsc.api.controller;

import cn.com.yiqi.wsc.Ro.*;
import cn.com.yiqi.wsc.api.controller.ro.CommonRO;
import cn.com.yiqi.wsc.common.Result;
import cn.com.yiqi.wsc.common.ResultStatusEnum;
import cn.com.yiqi.wsc.common.ResultUtil;
import cn.com.yiqi.wsc.dao.order.OrderLogisticsDao;
import cn.com.yiqi.wsc.entity.customer.Customer;
import cn.com.yiqi.wsc.entity.order.OrderLogistics;
import cn.com.yiqi.wsc.entity.order.OrderMain;
import cn.com.yiqi.wsc.enumeration.KdniaoStates;
import cn.com.yiqi.wsc.ro.KdniaoRO;
import cn.com.yiqi.wsc.service.SMS.SmsService;
import cn.com.yiqi.wsc.service.SMS.enumation.SmsCodeType;
import cn.com.yiqi.wsc.service.customer.CustomerService;
import cn.com.yiqi.wsc.service.file.dataobject.QiniuConfig;
import cn.com.yiqi.wsc.service.item.ItemService;
import cn.com.yiqi.wsc.service.kdniao.KdniaoTrackQueryAPI;
import cn.com.yiqi.wsc.service.order.impl.OrderServiceImpl;
import cn.com.yiqi.wsc.service.point.PointService;
import cn.com.yiqi.wsc.service.sysparams.SysParamsService;
import cn.com.yiqi.wsc.service.weixin.impl.WeixinPayImpl;
import cn.com.yiqi.wsc.util.KdniaoUtil;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.List;
/**
 *
 *@ClassName: ApiOrderController
 * Description: TODO
 * @author 会员系统组-林威
 * @date 2017/3/1 11:15
 *
 */
@RequestMapping("/api/order")
@Controller
@ResponseBody
public class ApiOrderController {

    @Autowired
    private KdniaoTrackQueryAPI kdniaoTrackQueryAPI;
    
    @Autowired
    CustomerService customerService;

    @Autowired
    OrderServiceImpl orderService;

    @Autowired
    WeixinPayImpl weixinService;

    @Autowired
    PointService pointService;

    @Autowired
    SysParamsService sysParamsService;

    @Autowired
    @Qualifier("xxtSmsService")
    SmsService smsService;

    @Autowired
    ItemService itemService;
    
    @Autowired
    QiniuConfig qiniuConfig;

    @Autowired
    private OrderLogisticsDao orderLogisticsDao;

    /**
     * 订单列表(大订单 / 全部订单，待发货，待付款)
     * */
    @RequestMapping("/list")
    public Result orderList(@RequestBody CommonRO ro){
        Result re;
        re = customerService.isExist(ro == null?null:ro.getUserId());
        if(!ResultUtil.isSuccess(re)){
            return re;
        }
        if(null == ro.getOrderState()){
            ro.setOrderState(1);
        }
        List<MainOrderVo> list = orderService.findOrderDetailByCustomerId(ro.getUserId(),ro.getOrderState());
        for(MainOrderVo vo:list){
        	for(OrderDetailVo v :vo.getMorderDetailVos()){
        		for(CartVO cv: v.getItems()){
        			cv.setItemUrl(qiniuConfig.getURL()+"/"+cv.getItemUrl());
        		}
        	}
        }
        re.putData("list",list);
        return ResultUtil.success(re);
    }

    /**
     * 订单列表(子订单 / 待收货，待付款)
     * */
    @RequestMapping("/detailList")
    public Result orderDtailList(@RequestBody CommonRO ro){
        Result re;
        re = customerService.isExist(ro == null?null:ro.getUserId());
        if(!ResultUtil.isSuccess(re) || null == ro.getUserId() || null == ro.getOrderState()){
            return ResultUtil.fail(re,"param error");
        }
        if(null == ro.getOrderState()){
            ro.setOrderState(1);
        }
        List<OrderDetailVo> list = orderService.findOrderDetails(ro.getUserId(),ro.getOrderState());

        	for(OrderDetailVo v : list){
        		for(CartVO cv: v.getItems()){
        			cv.setItemUrl(qiniuConfig.getURL()+"/"+cv.getItemUrl());
        		}
        	}
        re.putData("list",list);
        return ResultUtil.success(re);
    }

    /**
     * 全部订单
     * */
    @RequestMapping("/allList")
    public Result allOrderList(@RequestBody CommonRO ro){
        Result re;
        re = customerService.isExist(ro == null?null:ro.getUserId());
        if(!ResultUtil.isSuccess(re)){
            return re;
        }
        if(null == ro.getCurrentPage()){
            ro.setCurrentPage(1);
            ro.setPageSize(10);
        }
        PageInfo<MainOrderVo> pageInfo = orderService.findOrderDetailByCustomerIdPage(ro.getUserId(),ro.getCurrentPage(),ro.getPageSize());
        List<MainOrderVo> list = pageInfo.getList();
        for(MainOrderVo vo:list){
        	for(OrderDetailVo v :vo.getMorderDetailVos()){
        		for(CartVO cv: v.getItems()){
        			cv.setItemUrl(qiniuConfig.getURL()+"/"+cv.getItemUrl());
        		}
        	}
        }
        
        re.putData("data",pageInfo);
        return re;
    }

    /**
     * 订单详情
     * */
    @RequestMapping("/detail")
    public Result detail(@RequestBody CommonRO ro){
        Result re = new Result();
        if(null == ro.getId()){
            return ResultUtil.fail(re,"id不能为空");
        }
        OrderDetailVo vo = orderService.findOrderDetailById(ro.getId());
        if(null != vo.getAddressId()){
            AddressVO addressVO = customerService.findaddressByid(vo.getAddressId());
            re.putData("address",addressVO);
        }
        for(CartVO cv: vo.getItems()){
			cv.setItemUrl(qiniuConfig.getURL()+"/"+cv.getItemUrl());
		}
        re.putData("orderDetail",vo);
        return ResultUtil.success(re);
    }



    /**
     * 积分抵扣页面
     * */
    @RequestMapping("/usePoint")
    public Result userPoint(@RequestBody CommonRO ro){
        Result<Customer> re = customerService.isExist(ro.getUserId());
        if(!ResultUtil.isSuccess(re)){
            return re;
        }
        re.putData("point",re.getReturnValue().getPoint());
        re.putData("scale",sysParamsService.getPointPara().getPointScale());
        // 购物车商品 或者 立即购买的一件商品
        re.putData("canPoint",orderService.sumCanPoint(ro.getOrderId()));
        return re;
    }

    /**
     * 订单去付款
     * */
    @RequestMapping("/payDetail")
    private Result orderPayDetail(@RequestBody CommonRO ro){
        Result<Customer> re = customerService.isExist(ro.getUserId());
        if(!ResultUtil.isSuccess(re)){
            return re;
        }
        Result<OrderMain> result = orderService.isOrderCanPay(ro.getUserId(),ro.getOrderId());
        if(!ResultUtil.isSuccess(result)){
           return re;
        }
        //返回之前的冻结积分和余额并删除支付记录
        orderService.returnFrizee(ro.getUserId(),ro.getOrderId());

        OrderMain order = result.getReturnValue();
        if(null != ro.getOrderPoint()){
            PointParaDO pdo = sysParamsService.getPointPara();
            re.putData("total",order.getAmount().subtract(new BigDecimal(ro.getOrderPoint()+"").multiply(pdo.getPointScale())));
        }else {
            re.putData("total",order.getAmount());
        }
        re.putData("balance",re.getReturnValue().getBalance());
        return re;
    }


    /**
     * 结算付款
     *
     * */
    @RequestMapping("/prePay")
    public Result prePay(@RequestBody CommonRO ro, HttpServletRequest request){
        Result<Customer> re = customerService.isExist(ro.getUserId());
        if(!ResultUtil.isSuccess(re)){
            return re;
        }
        if((null != ro.getOrderPoint() && ro.getOrderPoint() <= 0) ||
                (null != ro.getOrderbalance() && ro.getOrderbalance().compareTo(BigDecimal.ZERO) <= 0 ) ){
            return ResultUtil.fail(re,"参数错误");
        }
        Result<OrderMain> result = orderService.isOrderCanPay(ro.getUserId(),ro.getOrderId());
        if(!ResultUtil.isSuccess(result)){
            return re;
        }
        //返回之前的冻结积分和余额并删除支付记录
        orderService.returnFrizee(ro.getUserId(),ro.getOrderId());

        Customer customer = re.getReturnValue();
        String ip;
        if (request.getHeader("x-forwarded-for") == null) {
            ip = request.getRemoteAddr();
        }else {
            ip = request.getHeader("x-forwarded-for");
        }
        //校验验证码
        if(null == ro.getCode() || !smsService.validateCode(SmsCodeType.orderPay,customer.getTel(),ro.getCode())){
            return ResultUtil.fail(re,"验证码错误");
        }

        //支付参数校验计算最终微信支付金额
        Result<BigDecimal> finalAmountResult = orderService.calWxAmout(customer.getId(),ro.getOrderId(),ro.getOrderbalance(),ro.getOrderPoint());
        if(!ResultUtil.isSuccess(finalAmountResult)){
            return finalAmountResult;
        }

        BigDecimal finalPay = finalAmountResult.getReturnValue();
        if(finalPay.compareTo(BigDecimal.ZERO) == 0){
            re.putData("paySuccess",true);
            return ResultUtil.success(re);
        }
        re = orderService.preCreate(ro.getOrderId(),finalPay,ip);
        return re;
    }

    /**
     * 查询订单状态
     * */
    @RequestMapping("/search")
    public Result search(@RequestBody CommonRO ro){
        if(null == ro.getUserId() || null ==ro.getOrderId()){
            return ResultUtil.fail(new Result(),"参数错误");
        }
        Result<OrderMain> result = orderService.isOrderCanPay(ro.getUserId(),ro.getOrderId());
        if(ResultUtil.isSuccess(result)){
            return ResultUtil.fail(result,"支付失败!");
        }else {
            return ResultUtil.success(result);
        }

    }


    /**
     * 微信支付回调
     * */
    @RequestMapping("/notifyHook")
    public String notifyWeixin(HttpServletRequest request) throws  Exception{

        String str = weixinService.notifyHook(request);
        return str;
    }

    /**
     * 微信支付短信
     * */
    @RequestMapping("/message")
    public Result sendMessage(@RequestBody CommonRO ro){
        Customer customer = customerService.selectById(ro.getUserId());
        Result re  = smsService.SendCode(SmsCodeType.orderPay,customer.getTel());
        return ResultUtil.success(re);
    }

    /**
     * subId查询退款商品
     * */
    @RequestMapping("/findBySubId")
    public Result findBysubId(@RequestBody CommonRO ro){
        Result re = new Result();
        re.putData("sub",orderService.findOrderSubDetail(ro.getId()));
        return re;
    }

    /**
     * 申请退款
     * */
    @RequestMapping("/refundApply")
    public Result refundApply(@RequestBody CommonRO ro){
        Result<Customer> re = customerService.isExist(ro.getUserId());
        if(!ResultUtil.isSuccess(re)){
            return re;
        }
        re = orderService.orderRefund(ro.getUserId(),ro.getOrderSubId(),ro.getRefundReson());
        if(!ResultUtil.isSuccess(re)){
            return re;
        }
        return re;
    }

    /**
     * 退款记录
     * */
    @RequestMapping("/refundList")
    public Result refundList(@RequestBody CommonRO ro){
        Result<Customer> re = customerService.isExist(ro.getUserId());
        if(!ResultUtil.isSuccess(re)){
            return re;
        }
        List<RefundItemVO> list = orderService.refundList(ro.getUserId(),null);
        re.putData("list",list);
        return re;
    }

    /**
     * 退款记录详情
     * */
    @RequestMapping("/refundDetail")
    public Result refundDetail(@RequestBody CommonRO ro){
        Result<Customer> re = customerService.isExist(ro.getUserId());
        if(!ResultUtil.isSuccess(re)){
            return re;
        }
        re.putData("refund",orderService.refundList(ro.getUserId(),ro.getId()));
        return re;
    }

    /**
     * 确认收货
     * */
    @RequestMapping("/comfirm")
    public Result comfirm(@RequestBody CommonRO ro){
        Result<Customer> re = customerService.isExist(ro.getUserId());
        if(!ResultUtil.isSuccess(re) || null == ro.getOrderId()){
            return ResultUtil.fail(re,"param error");
        }
        re = orderService.comfirmOrder(ro.getUserId(),ro.getOrderId());
        return re;
    }

    /**
     * 订单查看物流
     * */
    @RequestMapping("/orderTrance")
    public Result orderTrance(@RequestBody CommonRO ro){
        Result re = new Result();
        if(ro.getOrderId() == null){
            return ResultUtil.fail(re,"参数错误");
        }
        List<OrderLogistics> logisticses = orderLogisticsDao.getOrderLogisticsByOrderId(ro.getOrderId(),null);
        //查询订单跟踪信息
        for (OrderLogistics ol : logisticses) {
            String traces = null;
            traces = ol.getTraces();
            if (ol != null && StringUtils.isEmpty(traces)) {
                //如果没有订单跟踪信息
                String companyCode = ol.getLogisticsCompanyCode();
                String trackingNo = ol.getLogisticsTrackingNo();
                try {
                    KdniaoRO kdniaoRO = KdniaoUtil.json2Obj(kdniaoTrackQueryAPI.getOrderTracesByJson(companyCode, trackingNo));
                    if (kdniaoRO.isSuccess()) {
                        traces = JSON.toJSONString(kdniaoRO.getTraces());
                        if (KdniaoStates.签收.getState().equals(kdniaoRO.getState())) {
                            //如果订单已签收
                            //修改跟踪记录
                            OrderLogistics orderLogisticsForUpdate = new OrderLogistics();
                            orderLogisticsForUpdate.setId(ol.getId());
                            orderLogisticsForUpdate.setTraces(traces);
                            orderLogisticsDao.update(orderLogisticsForUpdate);
                        }
                        ol.setTraces(traces);
                    }
                } catch (Exception e) {
                	re.setStatus(ResultStatusEnum.服务器内部错误.getCode());
                	re.setErrMsg("获取订单跟踪信息失败");
                }
            }
        }
        re.putData("data",logisticses);
        return ResultUtil.success(re);
    }
}
